/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.mqtt.broker.utils

import io.netty.channel.Channel
import io.netty.handler.codec.mqtt.MqttMessage
import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader
import io.netty.util.AttributeKey

class MqttUtils {
	static val AttributeKey<String> clientIdAttr = AttributeKey.valueOf("CLIENT_ID");

	def static String getRemoteAddr(Channel channel) {
		if (null === channel) {
			return "";
		}
		var remote = channel.remoteAddress();
		val addr = remote !== null ? remote.toString() : "";
		if (addr.length() > 0) {
			var index = addr.lastIndexOf("/");
			if (index >= 0) {
				return addr.substring(index + 1);
			}
			return addr;
		}
		return "";
	}

	def static void setClientId(Channel channel, String clientId) {
		channel.attr(clientIdAttr).set(clientId);
	}

	def static String getClientId(Channel channel) {
		return channel.attr(clientIdAttr).get();
	}

	def static getMessageId(MqttMessage mqttMessage) {
		var varHeader = mqttMessage.variableHeader() as MqttMessageIdVariableHeader;
		return varHeader.messageId();
	}

	def static getQos(int qos1, int qos2) {
		if (qos1 < qos2) {
			return qos1;
		}
		return qos2;
	}

	def static session(String id) {
		return "mqtt-session-" + id;
	}
	
	def static qos2Message(String id) {
		return "mqtt-qos2-message" + id;
	}
}
